package com.netafull;

import java.util.ArrayList;
import java.util.List;

import com.netafull.adapter.CategoryAdapter;
import com.netafull.adapter.HomePageAdapter;
import com.netafull.analyze.AnalyzeXMLForCategory;
import com.netafull.analyze.AnalyzeXMLForHomepage;
import com.netafull.analyze.Category;
import com.netafull.analyze.News;
import com.netafull.db.CategoryService;
import com.netafull.util.CloseUtil;
import com.netafull.util.NetUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class HomePage extends ShowAdActivity {
	String path;// 首次请求的url地址
	String getCategoryUrl;// 首次请求的url地址
	ImageButton btn_menu;
	ImageButton btn_about;
	ListView listView;
	//添加popuWindow*********************************
	PopupWindow menuWindow;
	private boolean menu_display = false;
	LayoutInflater inflater;
	View layout;
	ImageButton category_close;//PopuWindow页面左右两个按键
	ImageButton category_refresh;
	
	ListView category_listview;
	//添加popuWindow*********************************
	Handler handler;
	View progress;
	View category_progress;
	
	CategoryService dbService;//数据库操作
	

	private List<News> list = new ArrayList<News>();
	private List<Category> categoryList = new ArrayList<Category>();

	HomePageAdapter homePageAdapter;
	CategoryAdapter categoryAdapter;

	public static final int HOMEPAGE_REQUEST_OK = 1;// 请求成功
	public static final int HOMEPAGE_REQUEST_ERR = -1;// 请求失败

	AnalyzeXMLForHomepage analyzeXMLForHomepage;
	AnalyzeXMLForCategory analyzeXMLForCategory;
	
	
	Thread t;
	
	boolean b = false;
	
	SharedPreferences sp;
	
	
	boolean flag = false;//用来标记数据库中是否有数据
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homepage);
		
		show();
		
		sp = getSharedPreferences("netafull",Context.MODE_PRIVATE);
		
		CloseUtil.activityList.add(HomePage.this);

		dbService = new CategoryService(HomePage.this);
		//path = getResources().getString(R.string.gettitlelist_url);
		path = getResources().getString(R.string.gettitlelist_url)+"&device=Android";
		
		//System.out.println("path="+path);
		getCategoryUrl = getResources().getString(R.string.getcategory_url)+"?device=Android";
		analyzeXMLForHomepage = new AnalyzeXMLForHomepage();
		analyzeXMLForCategory = new AnalyzeXMLForCategory();
		//listView = getListView();
		listView = (ListView) findViewById(R.id.homepage_list);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				b = true;
				// TODO Auto-generated method stub
				News news = list.get(position);
				Intent intent = new Intent(HomePage.this, NewsContent.class);
				Bundle bundle = new Bundle();
				bundle.putString("title", news.getTitle());
				bundle.putInt("id", news.getId());
				intent.putExtras(bundle);
				startActivityForResult(intent,100);
			}
			
		});
		listView.setScrollbarFadingEnabled(true);
		
		
		progress = findViewById(R.id.list_progress);
		

		btn_menu = (ImageButton) findViewById(R.id.homepage_button_left);
		btn_about = (ImageButton) findViewById(R.id.homepage_button_right);
		btn_menu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				openMenu();
			}
		});
		
		
		//****************************************************************
		inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.popu, null);
        
        category_listview = (ListView)layout.findViewById(R.id.category_list);
        
        category_close = (ImageButton) layout.findViewById(R.id.category_button_left);
        category_refresh = (ImageButton) layout.findViewById(R.id.category_button_right);
        category_close.setOnClickListener(new OnClickListener(){
        	
			@Override
			public void onClick(View v) {
				
				category_close.setEnabled(false);
				category_close.setClickable(false);
				category_listview.setAdapter(null);
				
				Log.d("logcate", "点击了close");
				System.out.println("点击了close");
				openMenu();
			}
        	
        });
        category_refresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.d("logcate", "点击了refresh");
				//刷新category页面
				//Toast.makeText(HomePage.this, "刷新category页面", Toast.LENGTH_LONG).show();
				category_progress.setVisibility(View.VISIBLE);
				
				category_refresh.setEnabled(false);
				category_close.setEnabled(false);
				category_refresh.setClickable(false);
				category_close.setClickable(false);
				System.out.println("1----->"+false);
				refreshCategoryList();
			}
		});
        //弹出menu 初始化
        menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        
        category_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				b = true;
				Category category = categoryList.get(position);
				final int categoryId = category.getId();
				openMenu();
				/*progress.setVisibility(View.VISIBLE);
				new Thread() {
					public void run() {
						list = analyzeXMLForHomepage.getRss(getResources().getString(R.string.gettitlelist_category_url)+categoryId);
						Message msg = new Message();
						if (list.size() != 0) {
							msg.what = HOMEPAGE_REQUEST_OK;
						} else {
							msg.what = HOMEPAGE_REQUEST_ERR;
						}
						handler.sendMessage(msg);
					};
				}.start();*/
				Intent intent = new Intent(HomePage.this, CategoryPage.class);
				Bundle bundle = new Bundle();
				bundle.putInt("category_id", categoryId);
				bundle.putString("category_name", category.getCategory_name());
				bundle.putInt("category_count", category.getTitle_count());
				intent.putExtras(bundle);
				HomePage.this.startActivityForResult(intent,100);
			}
		});
        //****************************************************************
		btn_about.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				b = true;
				Intent intent = new Intent(HomePage.this, About.class);
				HomePage.this.startActivityForResult(intent,100);
			}
		});

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case HOMEPAGE_REQUEST_OK:// 请求成功
					progress.setVisibility(View.GONE);
					showList();// 显示数据内容
					break;
				case HOMEPAGE_REQUEST_ERR:// 请求失败
					//showNetBusy();//显示请求超时提示框
					break;
				case 2:
					showCategoryList();
					
					category_refresh.setEnabled(true);
					category_refresh.setClickable(true);
					category_close.setEnabled(true);
					category_close.setClickable(true);
					System.out.println("3----->"+true);
					//categoryList = null;
					break;
				case 3://数据库中有数据
					showCategoryListFromDB();
					
					category_refresh.setEnabled(true);
					category_refresh.setClickable(true);
					category_close.setEnabled(true);
					category_close.setClickable(true);
					System.out.println("2----->"+true);
					break;
				case 4://刷新成功
					refreshShowCategoryList();
					
					if(!category_progress.isShown()){
						category_refresh.setEnabled(true);
						category_refresh.setClickable(true);
						category_close.setEnabled(true);
						category_close.setClickable(true);
						System.out.println("1----->"+true);
					}
					
					
					break;
				case -2://category页面数据请求超时
					if(flag){
						showCategoryListFromDB();
					}else {
						//openMenu();
						category_progress.setVisibility(View.GONE);
						showNetBusy();
					}
					break;
				}
			}
		};
		t = new Thread(){
			public void run() {
				System.out.println("开始请求数据"+path);
				Message msg = new Message();
				try {
					list = analyzeXMLForHomepage.getRss(path);
					if (list.size() != 0) {
						msg.what = HOMEPAGE_REQUEST_OK;
						System.out.println("数据请求成功");
					} 
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("数据请求超时");
					msg.what = HOMEPAGE_REQUEST_ERR;
				} finally {
					handler.sendMessage(msg);
				}
				
				
				
			};
		};
		t.start();
	}
	
	private void showNetBusy(){
		new AlertDialog.Builder(HomePage.this).setTitle(R.string.request_timeout)
			.setPositiveButton(R.string.determine, new AlertDialog.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if (t.isAlive()) {
						System.out.println("当前线程正在运行，强行中断");
						t.interrupt();
					}
					category_progress.setVisibility(View.VISIBLE);
					
					category_refresh.setEnabled(false);
					category_refresh.setClickable(false);
					category_close.setEnabled(false);
					category_close.setClickable(false);
					System.out.println("4----->"+false);
					
					refreshCategoryList();
				}
			})
			.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					openMenu();
				}
			}).create().show();
	}
	
	public void openMenu(){
		if(!menu_display){
			
			category_progress = layout.findViewById(R.id.category_list_progress);
			
			menuWindow.setAnimationStyle(R.style.PopupAnimation);
			menuWindow.showAtLocation(HomePage.this.getCurrentFocus(), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
			menuWindow.setFocusable(true);
			
			menuWindow.update();
			
			menu_display = true;
			if(dbService.getCount()==0){//当前数据库中没有数据
				//显示进度条************************************************************************
				flag = false;
				new Thread() {
					public void run() {
						Message message = new Message();
						try {
							categoryList = analyzeXMLForCategory.getRss(getCategoryUrl);
							if (categoryList.size() != 0) {
								message.what = 2;
								
							} else {
								message.what = -2;
							}
						} catch (Exception e) {
							e.printStackTrace();
							message.what = -2;
						}
						
						
						handler.sendMessage(message);
					};
				}.start();
			}else{
				//当前数据库中有数据，直接从数据库中读取
				flag = true;
				CategoryService service = new CategoryService(HomePage.this);
				categoryList = service.getAll();
				Message msg = new Message();
				msg.what = 3;
				/*for (Category c : categoryList) {
					System.out.println(c);
				}*/
				handler.sendMessage(msg);
			}
			
			
		}else{
			//如果当前已经为显示状态，则隐藏起来
			
			menuWindow.dismiss();
			menuWindow.setFocusable(false);
			menu_display = false;
			
		}
	}
	
	//刷新
	private void refreshCategoryList(){
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					categoryList = analyzeXMLForCategory.getRss(getCategoryUrl);
					if (categoryList.size() != 0) {
						message.what = 4;
						
					} else {
						message.what = -2;
					}
				} catch (Exception e) {
					System.out.println("超时--->");
					message.what = -2;
					e.printStackTrace();
				} finally{
					System.out.println("homepage------>"+message.what);
					handler.sendMessage(message);
				}
				
			};
		}.start();
	}

	// 显示列表
	private void showList() {
		homePageAdapter = new HomePageAdapter(list, HomePage.this);
		
		//setListAdapter(homePageAdapter);
		listView.setAdapter(homePageAdapter);
		
	}
	private void showCategoryList() {
		
		categoryAdapter = new CategoryAdapter(categoryList, HomePage.this);
		
		category_listview.setAdapter(categoryAdapter);
		category_progress.setVisibility(View.GONE);
		CategoryService service = new CategoryService(HomePage.this);
		service.save(categoryList);//保存到数据库中
		/*for (Category c : categoryList) {
			System.out.println(c);
		}*/
		
	}
	
	private void refreshShowCategoryList() {
		
		categoryAdapter = new CategoryAdapter(categoryList, HomePage.this);
		
		category_listview.setAdapter(categoryAdapter);
		
		CategoryService service = new CategoryService(HomePage.this);
		//service.save(categoryList);//更新到数据库
		service.update(categoryList);
		category_progress.setVisibility(View.GONE);
		
		
	}
	//从数据库中读取数据并显示
	private void showCategoryListFromDB() {
		System.out.println("这是从数据库来的消息");
		categoryAdapter = new CategoryAdapter(dbService.getAll(), HomePage.this);
		
		category_listview.setAdapter(categoryAdapter);
		category_progress.setVisibility(View.GONE);
	}

	// 当点击某个Item时加载
	/*@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		News news = list.get(position);
		Intent intent = new Intent(this, NewsContent.class);
		Bundle bundle = new Bundle();
		bundle.putString("title", news.getTitle());
		bundle.putInt("id", news.getId());
		intent.putExtras(bundle);
		startActivity(intent);
	}*/
	
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(HomePage.this).setTitle(R.string.out)
					.setPositiveButton(R.string.determine, new AlertDialog.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							if (t.isAlive()) {
								System.out.println("当前线程正在运行，强行中断");
								t.interrupt();
							}
							HomePage.this.finish();
						}
					})
					.setNegativeButton(R.string.quxiao, new AlertDialog.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					}).create().show();
		}
		return false;
	}

	/*@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		init();
	}*/
	/*public void init() {
		// TODO Auto-generated method stub
		//检查网络
		if(!NetUtil.checkNet(this))
		{
		  	NetUtil.alertNetError(this);
			
		}
	}*/
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!NetUtil.checkNet(this)) {
			NetUtil.alertNetError(this);
		}
	}
	
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		if(!b){
			if(sp!=null){
				Editor editor = sp.edit();
				editor.clear();
				editor.commit();
			}
			System.out.println("开始销毁Activity");
			CloseUtil.closeActivity();
		}else{
			System.out.println("没有销毁Activity");
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		b = false;
	}
	
}
